/*
 * Copyright 2013 Glassy Cinema.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package hu.glassy.web.component.behaviour;

import org.apache.wicket.Component;
import org.apache.wicket.behavior.AbstractAjaxBehavior;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.model.ResourceModel;

/**
 * Implements various additional behaviours for the form components
 *
 * @author Alexander Molnár <molnar.alexander@sonrisa.hu>
 * @param <T>
 */
public class FormComponentBehavior<T> extends AbstractAjaxBehavior
{

  private static final long serialVersionUID = 3524435525047372565L;

  @Override
  protected void onComponentRendered()
  {
    final Component component = getComponent();
    if (component instanceof FormComponent<?>)
    {
      final FormComponent<?> fc = (FormComponent<?>) getComponent();
      if (fc.hasErrorMessage())
      {
        String errorMessage;

        if (fc.hasErrorMessage())
        {
          FeedbackMessage message = fc.getFeedbackMessages().first(FeedbackMessage.ERROR);
          errorMessage = message.getMessage().toString();
        }
        else
        {
          errorMessage = new ResourceModel("registration.error.invalidinput").getObject();
        }
        fc.getResponse().write("<small class=\"text-danger\">" + errorMessage + "</small>");
      }
    }
  }

  @Override
  protected void onComponentTag(final ComponentTag tag)
  {
    final Component component = getComponent();
    if (component instanceof FormComponent<?>)
    {
      final FormComponent<?> fc = (FormComponent<?>) component;

      // Add invalid class
      if (!fc.isValid())
      {
        tag.append("class", "has-error", " ");
      }

      // Add required class
      if (fc.isRequired())
      {
        tag.append("class", "required", " ");
      }
    }
  }

  @Override
  public void onRequest()
  {
    // Do nothing
  }
}
